﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace WinForm.Validation
{
    public class WinFormIntegrateValidator : IntegrateValidator
    {
        private IList<IValidator> validators;
        private ErrorProvider errorProvider;

        public static WinFormIntegrateValidator CreateInstance()
        {
            return new WinFormIntegrateValidator();
        }

        public WinFormIntegrateValidator AddNotBlankFieldValidator(params Control[] controls)
        {
            foreach (Control item in controls)
            {
                AddValidators(new NotBlankFieldValidator(item));
            }
            return this;
        }

        public bool Validate()
        {
            bool result = true;
            if (null != this.validators && validators.Count > 1)
            {
                foreach (IValidator item in this.validators)
                {
                    if (item.Owner.CausesValidation)
                    {
                        if (!item.Validate())
                        {
                            result = false;
                        }
                        SetMessage(item);
                    }
                }
            }
            return result;
        }

        public void AddValidators(params IValidator[] validators)
        {
            if (null == validators)
            {
                return;
            }

            if (null == this.validators)
            {
                this.validators = new List<IValidator>();
            }

            foreach (IValidator item in validators)
            {
                this.validators.Add(item);
            }
        }

        private void SetMessage(IValidator validator)
        {
            if (null == errorProvider)
            {
                errorProvider = new ErrorProvider();
            }
            errorProvider.SetError(validator.Owner, validator.Message);
        }
    }
}
